package com.liyongjian.xhban.api;

import java.awt.image.BufferedImage;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.liyongjian.xhban.dto.AjaxResponse;


@Controller
@RequestMapping("/api/upload")
public class UploadController extends BaseController {


    @ResponseBody
    @RequestMapping(path = "file", method = RequestMethod.POST)
    public AjaxResponse uploadFile(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        AjaxResponse ajax = new AjaxResponse(true);
        String path = "";
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Map<String, String> map = new HashMap<String, String>();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile imgFile = entity.getValue();
            String tfsName = imgFile.getOriginalFilename();

            BufferedImage bi = ImageIO.read(imgFile.getInputStream());
            String fileName = new StringBuilder("pic_album_ad_")
                    .append(new SimpleDateFormat("yyyyMMddhhmmssS").format(new Date()))
                    .append(RandomUtils.nextLong(1000, 10000)).append("_").append(bi.getWidth())
                    .append("x").append(bi.getHeight()).toString();

            String suffix = tfsName.indexOf(".") != -1
                    ? tfsName.substring(tfsName.lastIndexOf("."), tfsName.length()) : null;
            fileName = fileName + suffix;

            // 保存本地文件
            String uploadDir = suffix.replaceAll("\\.", "");
            String tempPath = fileRootPath + "/" + uploadDir;
            File saveDirFile = new File(tempPath);
            if (!saveDirFile.exists()) {
                saveDirFile.mkdirs();
            }

            File file = new File(tempPath + "/" + fileName);
            imgFile.transferTo(file);
            path = fileRootUrl + "/" + uploadDir + "/" + fileName;
            map.put("name", fileName);
            map.put("path", path);
        }
        return ajax.setObj(path);
    }



}
